package com.service.infoEntry.controller;

import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;
import com.service.config.utils.Result;
import com.service.config.utils.UserTokenManager;
import com.service.infoEntry.dto.TeamInfoDto;
import com.service.infoEntry.dto.UserDto;
import com.service.infoEntry.service.TeamService;
import com.service.infoEntry.vo.RoleVo;
import com.service.infoEntry.vo.TeamVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static com.service.infoEntry.constant.Constant.*;

@CrossOrigin
@RestController()
@RequestMapping("/team")
@Api(value = "团队相关接口")
public class TeamController {

    @Resource
    RedisUtil redisUtil;
    @Resource
    TeamService teamService;

    @ApiOperation(value = "创建团队")
    @RequestMapping(value = "/createTeam",method = RequestMethod.POST)
    @ResponseBody
    public Result creatorTeam(@RequestBody TeamInfoDto teamInfoDto,
                               @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                teamService.createTeam(teamInfoDto,userId);
                return Result.ok();
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 团队添加用户
     * @param teamId 团队id
     * @param id 被添加用户id
     * @param cloudAuthToken token
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "团队添加用户")
    @RequestMapping(value = "/addUser2Team",method = RequestMethod.POST)
    @ResponseBody
    public Result addUser2Team(@RequestParam("teamId") String teamId,
                              @RequestParam("userId") String id,
                              @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                boolean b = checkTeamIsExist(teamId);
                if (b)
                {
                    return teamService.addUser2Team(teamId, id, userDto.getId());
                }
                return Result.failure(TEAM_NOT_EXIST,TEAM_DOES_NOT_EXIST);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 移除团队用户
     * @param teamId 团队id
     * @param id 被移除用户的用户名
     * @param cloudAuthToken token
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "移除团队用户")
    @RequestMapping(value = "/removeUserFromTeam",method = RequestMethod.POST)
    @ResponseBody
    public Result removeUserFromTeam(@RequestParam("teamId") String teamId,
                                     @RequestParam("userId") String id,
                              @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                boolean b = checkTeamIsExist(teamId);
                if(b)
                {
                    Integer role = checkUserAuthority(userDto.getId(), teamId);
                    if(null == role)
                    {
                        return Result.failure(USER_NOT_IN_TEAM, "当前用户不在该团队中");
                    }
                    if(role == 1 || role == 2)
                    {
                        return teamService.removeUserFromTeam(teamId,role,id);
                    }
                    return Result.failure(USER_NO_AUTHORITY, "当前用户权限不足");
                }
                return Result.failure(TEAM_NOT_EXIST,TEAM_DOES_NOT_EXIST);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 团队创建者给团队添加管理员
     * @param teamId 团队id
     * @param id 管理员id
     * @param cloudAuthToken token
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "创建者添加管理员")
    @RequestMapping(value = "/addAdminInTeam",method = RequestMethod.POST)
    @ResponseBody
    public Result addAdminInTeam(@RequestParam("teamId") String teamId,
                                 @RequestParam("userId") String id,
                              @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                boolean b = checkTeamIsExist(teamId);
                if(b)
                {
                    Integer role = checkUserAuthority(userDto.getId(), teamId);
                    if(null == role)
                    {
                        return Result.failure(USER_NOT_IN_TEAM, "当前用户不在该团队中");
                    }
                    if(role != 1)
                    {
                        return Result.failure(USER_NO_AUTHORITY, "当前用户权限不足");
                    }
                    return teamService.addAdminInTeam(teamId,id);
                }
                return Result.failure(TEAM_NOT_EXIST,TEAM_DOES_NOT_EXIST);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 团队创建者移除团队管理员
     * @param teamId 团队id
     * @param id 管理员id
     * @param cloudAuthToken token
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "创建者移除管理员")
    @RequestMapping(value = "/removeAdminInTeam",method = RequestMethod.POST)
    @ResponseBody
    public Result removeAdminInTeam(@RequestParam("teamId") String teamId,
                                 @RequestParam("userId") String id,
                                 @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                boolean b = checkTeamIsExist(teamId);
                if(b)
                {
                    Integer role = checkUserAuthority(userDto.getId(), teamId);
                    if(null == role)
                    {
                        return Result.failure(USER_NOT_IN_TEAM, "当前用户不在该团队中");
                    }
                    if(role ==1 || role == 2)
                    {
                        return teamService.removeAdminInTeam(teamId,id);
                    }
                    return Result.failure(USER_NO_AUTHORITY, "当前用户权限不足");
                }
                return Result.failure(TEAM_NOT_EXIST,TEAM_DOES_NOT_EXIST);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "查询用户所有团队")
    @RequestMapping(value = "/queryTeams",method = RequestMethod.GET)
    @ResponseBody
    public Result queryTeams(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                List<TeamVo> teams = teamService.queryTeamsWithRole(userId);
                return Result.ok().setData(teams);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 查询当前团队中的所有用户
     * @param
     * @return
     */
    @RequestMapping(value =  "/queryAllUserInTeam",method = RequestMethod.GET,produces="application/json")
    @ApiOperation(value = "查询当前团队所有用户")
    @ResponseBody
    public Result queryAllUserInTeam(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                     @RequestParam("page") Integer page,
                                     @RequestParam("teamId") String teamId) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                boolean b = checkTeamIsExist(teamId);
                if(b)
                {
                    Map<String,Object> map= teamService.queryAllUserInTeam(teamId,userId,page);
                    return Result.ok().setData(map);
                }
                return Result.failure(TEAM_NOT_EXIST,TEAM_DOES_NOT_EXIST);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 解散团队
     * @param teamId 团队id
     * @param cloudAuthToken token
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "解散团队")
    @RequestMapping(value = "/removeTeam",method = RequestMethod.POST)
    @ResponseBody
    public Result removeTeam(@RequestParam("teamId") String teamId,
                                    @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                boolean b = checkTeamIsExist(teamId);
                if(b)
                {
                    Integer role = checkUserAuthority(userDto.getId(), teamId);
                    if(null == role)
                    {
                        return Result.failure(USER_NOT_IN_TEAM, "当前用户不在该团队中");
                    }
                    if(role != 1)
                    {
                        return Result.failure(USER_NO_AUTHORITY, "当前用户权限不足");
                    }
                    return teamService.removeTeam(teamId);
                }
                return Result.failure(TEAM_NOT_EXIST,TEAM_DOES_NOT_EXIST);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 普通管理员转移管理权限
     * @param teamId
     * @param id 管理员权限被转移的用户
     * @param cloudAuthToken
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "普通管理员转移管理权限")
    @RequestMapping(value ="/changeAdmin",method = RequestMethod.POST)
    @ResponseBody
    public Result changeAdmin(@RequestParam("teamId") String teamId,
                             @RequestParam("userId") String id,
                             @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                boolean b = checkTeamIsExist(teamId);
                if(b)
                {
                    Integer role = checkUserAuthority(userDto.getId(), teamId);
                    if(null == role)
                    {
                        return Result.failure(USER_NOT_IN_TEAM, "当前用户不在该团队中");
                    }
                    if(role != 2)
                    {
                        return Result.failure(USER_NO_AUTHORITY, "当前用户权限不足");
                    }
                    return teamService.changeAdmin(teamId,userDto.getId(),id);
                }
                return Result.failure(TEAM_NOT_EXIST,TEAM_DOES_NOT_EXIST);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 切换团队
     * @param teamId
     * @param cloudAuthToken
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "切换团队")
    @RequestMapping(value ="/changeTeam",method = RequestMethod.POST)
    @ResponseBody
    public Result changeTeam(@RequestParam("teamId") String teamId,
                           @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                boolean b = checkTeamIsExist(teamId);
                if(b)
                {
                    TeamVo teamVo = teamService.changeTeam(teamId, userId);
                    return Result.ok().setData(teamVo);
                }
                return Result.failure(TEAM_NOT_EXIST,TEAM_DOES_NOT_EXIST);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 退出团队
     * @param teamId
     * @param cloudAuthToken
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "退出团队")
    @RequestMapping(value ="/exitTeam",method = RequestMethod.POST)
    @ResponseBody
    public Result exitTeam(@RequestParam("teamId") String teamId,
                              @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                boolean b = checkTeamIsExist(teamId);
                if(b)
                {
                    Integer role = checkUserAuthority(userDto.getId(), teamId);
                    if(null == role)
                    {
                        return Result.failure(USER_NOT_IN_TEAM, "当前用户不在该团队中");
                    }
                    if(role == 1 || role==2)
                    {
                        return Result.failure(CREATOR_NOT_EXIT, CREATOR_OR_ADMIN_NOT_EXIT_THE_TEAM);
                    }
                    return teamService.exitTeam(teamId,userDto.getId());
                }
                return Result.failure(TEAM_NOT_EXIST,TEAM_DOES_NOT_EXIST);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "当前用户在当前团队中的所有权限")
    @RequestMapping(value ="/queryPermissionsInTeam",method = RequestMethod.GET)
    @ResponseBody
    public Result queryPermissionsInTeam(@RequestParam("teamId")String teamId,
            @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                RoleVo roleVo = teamService.queryPermissionsInTeam(teamId,userId);
                return Result.ok().setData(roleVo);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 判断用户在团队中的角色:1、创建者;2、管理员;3、普通用户
     * @param userId
     * @param teamId
     * @return
     */
    public Integer checkUserAuthority(String userId, String teamId)
    {
        Integer role = teamService.checkUserAuthority(userId,teamId);
        return role;
    }

    public boolean checkTeamIsExist(String teamId)
    {
        Integer count = teamService.checkTeamIsExist(teamId);
        return count>0?true:false;
    }
}
